package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Enterprise;
import com.antdesignbackend.backend.entity.HarmlessReport;
import com.antdesignbackend.backend.entity.entityVo.HarmlessReportVo;
import com.antdesignbackend.backend.service.EnterpriseService;
import com.antdesignbackend.backend.service.HarmlessReportService;
import com.antdesignbackend.backend.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/harmlessReport")
public class HarmlessReportController extends BaseController {
    @Autowired
    HarmlessReportService harmlessReportService;

    @Autowired
    PermissionService permissionService;
    @Autowired
    EnterpriseService enterpriseService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer menuId;

    @GetMapping("/index")
    @AuthToken
    public String ProductionIndex(String menuId, Model model) {
        this.menuId = Integer.parseInt(menuId);
        model.addAttribute("type",getLoginAnimalTypes());
        return "harmless/harmlessReport";
    }
    /**
     * 分页查询
     * @param harmlessReportVo
     * @return
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody HarmlessReportVo harmlessReportVo, HttpServletRequest request) {
        ReturnVO result = new ReturnVO();
        List<HarmlessReportVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<HarmlessReportVo> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Enterprise> enterpriseQueryWrapper=new QueryWrapper<>();
            queryWrapper.eq("eid",getLoginEnterpriseId());
            if (harmlessReportVo.getTimeInterval() != null && !harmlessReportVo.getTimeInterval().equals("")){
                String[] str=harmlessReportVo.getTimeInterval().split(" - ");
                String star=str[0];
                String end=str[1];
                queryWrapper.between("declareTime",star,end);
            }
            if (harmlessReportVo.getStatus() != null && harmlessReportVo.getStatus() != -1){
                queryWrapper.eq("status",harmlessReportVo.getStatus());
            }
            queryWrapper.orderByDesc("declareTime");
            //先统计满足条件的数据总数，因为sql 不包括排序
            int total=harmlessReportService.count(queryWrapper);
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= harmlessReportService.search(queryWrapper,new Page<>(harmlessReportVo.getPageIndex(),harmlessReportVo.getPageSize()));
                if (datalist.size() > 0){
                    for (HarmlessReportVo harmlessReportVo1:datalist){
                        if (harmlessReportVo1.getImg() != null && !harmlessReportVo1.getImg().equals("")){
                            harmlessReportVo1.setImg(WebConfig.host+"images/"+harmlessReportVo1.getImg());
                        }
                        if (harmlessReportVo1.getDeclareImage() != null && !harmlessReportVo1.getDeclareImage().equals("")){
                            harmlessReportVo1.setDeclareImageUrl(WebConfig.host+"images/"+harmlessReportVo1.getDeclareImage());
                        }
                        if (harmlessReportVo1.getHarmlessId() != null && !harmlessReportVo1.getHarmlessId().equals("")){
                            enterpriseQueryWrapper.eq("EnterpriseId",harmlessReportVo1.getHarmlessId());
                            Enterprise enterprise=enterpriseService.getOne(enterpriseQueryWrapper);
                            harmlessReportVo1.setHarmlessName(enterprise.getEnterpriseName());
                        }
                    }
                }
                //得到当前菜单具备的功能权限
                //获得当前角色
//                Object roleID = request.getSession().getAttribute("RoleID");
//                List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
//                datalist.forEach(model -> model.setButtonList(list));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }
    @PostMapping("/tableSearchMe/{eid}")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearchMe(@PathVariable("eid") int eid) {
        ReturnVO result = new ReturnVO();
        List<HarmlessReportVo> datalist=new ArrayList<>();
        try {
            QueryWrapper<HarmlessReportVo> queryWrapper = new QueryWrapper<>();
            QueryWrapper<Enterprise> enterpriseQueryWrapper=new QueryWrapper<>();
            queryWrapper.eq("eid",eid);
            int total=harmlessReportService.count(queryWrapper);
            HarmlessReportVo harmlessReportVo=new HarmlessReportVo();
            result.setTotal(total);
            //再查询
            if(total>0)
            {
                datalist= harmlessReportService.search(queryWrapper,new Page<>(harmlessReportVo.getPageIndex(),harmlessReportVo.getPageSize()));
                if (datalist.size() > 0){
                    for (HarmlessReportVo harmlessReportVo1:datalist){
                        if (harmlessReportVo1.getImg() != null && !harmlessReportVo1.getImg().equals("")){
                            harmlessReportVo1.setImg(WebConfig.host+"images/"+harmlessReportVo1.getImg());
                        }
                        if (harmlessReportVo1.getDeclareImage() != null && !harmlessReportVo1.getDeclareImage().equals("")){
                            harmlessReportVo1.setDeclareImage(WebConfig.host+"images/"+harmlessReportVo1.getDeclareImage());
                        }
                        if (harmlessReportVo1.getHarmlessId() != null && !harmlessReportVo1.getHarmlessId().equals("")){
                            enterpriseQueryWrapper.eq("EnterpriseId",harmlessReportVo1.getHarmlessId());
                            Enterprise enterprise=enterpriseService.getOne(enterpriseQueryWrapper);
                            harmlessReportVo1.setHarmlessName(enterprise.getEnterpriseName());
                        }
                    }
                }
                //得到当前菜单具备的功能权限
                //获得当前角色
//                Object roleID = request.getSession().getAttribute("RoleID");
//                List<Button> list = permissionService.filterPermission(String.valueOf(roleID), menuId);
//                datalist.forEach(model -> model.setButtonList(list));
            }
            result.setData(datalist);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return result;
    }

    /**
     * 添加
     * @param harmlessReport
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    @AuthToken
    public ReturnVO add(@RequestBody HarmlessReport harmlessReport, HttpServletRequest request) {
        try {
            //获得用户id
            harmlessReport.setDeclareUser(getLoginUserId());
            //获得企业
            harmlessReport.setEid(getLoginEnterpriseId());
            //设置申报日期
            harmlessReport.setDeclareTime(new Date());
            //设置初始状态
            harmlessReport.setStatus(0);
            harmlessReport.setAnimalTypes(getLoginAnimalTypes());
            int sum = 0;
            if (getLoginAnimalTypes() == 1){
                int specices = 0;
                int reserve = 0;
                int menstruation = 0;
                int lactation = 0;
                int conservation = 0;
                int commodity = 0;
                if (harmlessReport.getSpecies() != null)
                    specices = harmlessReport.getSpecies();
                if (harmlessReport.getReserve() != null)
                    reserve = harmlessReport.getReserve();
                if (harmlessReport.getMenstruation() != null)
                    menstruation = harmlessReport.getMenstruation();
                if (harmlessReport.getLactation() != null)
                    lactation = harmlessReport.getLactation();
                if (harmlessReport.getConservation() != null)
                    conservation = harmlessReport.getConservation();
                if (harmlessReport.getCommodity() != null)
                    commodity = harmlessReport.getCommodity();
                sum += specices+reserve+menstruation+lactation+conservation+commodity;
            }else {
                sum = harmlessReport.getLivestock();
            }
            harmlessReport.setDead(sum);
            harmlessReportService.save(harmlessReport);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 修改
     * @param harmlessReport
     * @return
     */
    @PostMapping("/edit")
    @ResponseBody
    @AuthToken
    public ReturnVO edit(@RequestBody HarmlessReport harmlessReport) {
        try {
            int sum = 0;
            if (getLoginAnimalTypes() == 1){
                int specices = 0;
                int reserve = 0;
                int menstruation = 0;
                int lactation = 0;
                int conservation = 0;
                int commodity = 0;
                if (harmlessReport.getSpecies() != null)
                    specices = harmlessReport.getSpecies();
                if (harmlessReport.getReserve() != null)
                    reserve = harmlessReport.getReserve();
                if (harmlessReport.getMenstruation() != null)
                    menstruation = harmlessReport.getMenstruation();
                if (harmlessReport.getLactation() != null)
                    lactation = harmlessReport.getLactation();
                if (harmlessReport.getConservation() != null)
                    conservation = harmlessReport.getConservation();
                if (harmlessReport.getCommodity() != null)
                    commodity = harmlessReport.getCommodity();
                sum += specices+reserve+menstruation+lactation+conservation+commodity;
            }else {
                sum = harmlessReport.getLivestock();
            }
            harmlessReport.setDead(sum);
            harmlessReportService.updateById(harmlessReport);
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }

    /**
     * 删除
     * @param harmlessReport
     * @return
     */
    @PostMapping("/del")
    @ResponseBody
    @AuthToken
    public ReturnVO del(@RequestBody HarmlessReport harmlessReport) {
        try {
            harmlessReportService.removeById(harmlessReport.getHarmlessReportID());
            return new ReturnVO();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }
}
